<template>
  <div class="product-detail-container">
    <!-- 返回按钮 -->
    <div class="breadcrumb-section">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/products' }">商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>{{ product?.name || '商品详情' }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 商品详情内容 -->
    <div class="product-content" v-loading="loading" element-loading-text="加载中...">
      <div v-if="product" class="product-info">
        <!-- 商品图片区域 -->
        <div class="product-images">
          <div class="main-image-container">
            <img :src="currentImage" :alt="product.name" class="main-image" />
          </div>
          <div class="thumbnail-container">
            <img
              v-for="(image, index) in product.images"
              :key="index"
              :src="image"
              :alt="`商品图片${index + 1}`"
              class="thumbnail"
              :class="{ active: currentImage === image }"
              @click="currentImage = image"
            />
          </div>
        </div>

        <!-- 商品信息区域 -->
        <div class="product-details">
          <h1 class="product-title">{{ product.name }}</h1>
          <p class="product-subtitle">{{ product.description || '' }}</p>

          <!-- 价格信息 -->
          <div class="price-section">
            <div class="current-price">￥{{ product.price.toFixed(2) }}</div>
            <div v-if="product.originalPrice > product.price" class="original-price">
              ￥{{ product.originalPrice.toFixed(2) }}
            </div>
            <div v-if="product.originalPrice > product.price && shouldShowDiscount(calculateDiscountRate(product.price, product.originalPrice))" class="discount-tag">
              {{ calculateDiscountRate(product.price, product.originalPrice) }}折
            </div>
          </div>

          <!-- 商品评价 -->
          <div class="rating-section" v-if="product.rating">
            <el-rate :model-value="product.rating" disabled show-score text-color="#ff9900" />
            <span class="review-count">{{ product.reviewCount || 0 }}条评价</span>
          </div>

          <!-- 商品属性 -->
          <div class="product-attributes">
            <div class="attribute-row">
              <span class="label">品牌:</span>
              <span class="value">{{ product.brandName || '无品牌' }}</span>
            </div>
            <div class="attribute-row">
              <span class="label">分类:</span>
              <span class="value">{{ product.categoryName || '无分类' }}</span>
            </div>
            <div class="attribute-row">
              <span class="label">库存:</span>
              <span class="value" :class="{ 'low-stock': product.stock <= 10 }">
                {{ product.stock > 0 ? `${product.stock}件` : '已售罄' }}
              </span>
            </div>
          </div>

          <!-- 规格选择 -->
          <div class="spec-section" v-if="product.colors && product.colors.length > 0">
            <h3>选择规格:</h3>
            <div class="spec-group">
              <span class="spec-label">颜色:</span>
              <div class="spec-options">
                <el-button
                  v-for="color in product.colors"
                  :key="color.colorId"
                  :type="selectedSpecs['color'] === color.colorName ? 'primary' : 'default'"
                  size="small"
                  @click="selectSpec('color', color.colorName)"
                >
                  {{ color.colorName }}
                </el-button>
              </div>
            </div>
            <div class="spec-group" v-if="product.sizes && product.sizes.length > 0">
              <span class="spec-label">尺码:</span>
              <div class="spec-options">
                <el-button
                  v-for="size in product.sizes"
                  :key="size.sizeId"
                  :type="selectedSpecs['size'] === size.shoeSize ? 'primary' : 'default'"
                  size="small"
                  @click="selectSpec('size', size.shoeSize)"
                >
                  {{ size.shoeSize }}
                </el-button>
              </div>
            </div>
          </div>

          <!-- 数量选择 -->
          <div class="quantity-section">
            <span class="label">数量:</span>
            <el-input-number
              v-model="quantity"
              :min="1"
              :max="Math.max(1, product.stock)"
              :disabled="product.stock === 0"
            />
            <span class="stock-info">库存{{ product.stock }}件</span>
          </div>

          <!-- 购买按钮 -->
          <div class="action-buttons">
            <el-button
              type="primary"
              size="large"
              :disabled="product.stock === 0"
              @click="showAttributeModal"
            >
              <el-icon>
                <ShoppingCart />
              </el-icon>
              加入购物车
            </el-button>
            <el-button
              type="danger"
              size="large"
              :disabled="product.stock === 0"
              @click="showBuyNowModal"
            >
              立即购买
            </el-button>
            <el-button
              :type="isWishlisted ? 'warning' : 'default'"
              size="large"
              @click="toggleWishlist"
            >
              <el-icon>
                <StarFilled v-if="isWishlisted" />
                <Star v-else />
              </el-icon>
              {{ isWishlisted ? '已收藏' : '收藏' }}
            </el-button>
          </div>

          <!-- 移动端购买按钮 -->
          <div class="mobile-action-buttons">
            <el-button
              type="primary"
              size="large"
              :disabled="product.stock === 0"
              @click="showAttributeModal"
              class="mobile-btn"
            >
              <el-icon>
                <ShoppingCart />
              </el-icon>
              加入购物车
            </el-button>
            <el-button
              type="danger"
              size="large"
              :disabled="product.stock === 0"
              @click="showBuyNowModal"
              class="mobile-btn"
            >
              立即购买
            </el-button>
            <el-button
              :type="isWishlisted ? 'warning' : 'default'"
              size="large"
              @click="toggleWishlist"
              class="mobile-btn"
            >
              <el-icon>
                <StarFilled v-if="isWishlisted" />
                <Star v-else />
              </el-icon>
              {{ isWishlisted ? '已收藏' : '收藏' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品详情介绍 -->
    <div class="product-description" v-if="product">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="商品详情" name="description">
          <div class="description-content" v-html="product.description || '暂无商品详情'"></div>
        </el-tab-pane>
        <el-tab-pane label="规格参数" name="specs">
          <div class="specs-content">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="商品名称">
                {{ product.name }}
              </el-descriptions-item>
              <el-descriptions-item label="品牌">
                {{ product.brandName }}
              </el-descriptions-item>
              <el-descriptions-item label="分类">
                {{ product.categoryName }}
              </el-descriptions-item>
              <el-descriptions-item label="类型">
                {{ product.typeName }}
              </el-descriptions-item>
              <el-descriptions-item label="库存"> {{ product.stock }}件 </el-descriptions-item>
              <el-descriptions-item label="销量"> {{ product.sales }}件 </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>
        <el-tab-pane label="用户评价" name="reviews">
          <div class="reviews-content">
            <ProductReviews v-if="product" :product-id="product.productId" />
            <div v-else class="loading-placeholder">加载中...</div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 相关商品推荐 -->
    <div class="related-products" v-if="relatedProducts.length > 0">
      <h2 class="section-title">相关推荐</h2>
      <div class="products-grid">
        <ProductCard
          v-for="relatedProduct in relatedProducts"
          :key="relatedProduct.productId"
          :product="relatedProduct"
          @add-to-cart="handleAddToCart"
        />
      </div>
    </div>

    <!-- 商品属性选择弹窗 -->
    <ProductAttributeModal
      v-model:visible="attributeModalVisible"
      :product="product"
      :buy-now-mode="isBuyNowMode"
      @success="handleAddToCartSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watchEffect, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ShoppingCart, Star, StarFilled } from '@element-plus/icons-vue'
import { productService } from '@/api'
import { useCartStore } from '@/stores/cart'
import ProductCard from '@/components/ProductCard.vue'
import ProductReviews from '@/components/ProductReviews.vue'
import ProductAttributeModal from '@/components/ProductAttributeModal.vue'
import type { Product, ProductDetail } from '@/types/product'
import { createLogger } from '@/utils/logger'
import { useAuthStore } from '@/stores/auth'
import { useAuthModalStore } from '@/stores/authModal'
import { addToWishlist, removeFromWishlist, checkWishlistStatus } from '@/api/wishlistService'
import { shouldShowDiscount, calculateDiscountRate } from '@/utils/discountUtils'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const authStore = useAuthStore()
const authModal = useAuthModalStore()
const productLogger = createLogger('ProductDetail')

// 响应式数据
const product = ref<ProductDetail | null>(null)
const relatedProducts = ref<Product[]>([])
const isComponentMounted = ref(true)
const loading = ref(false)
const quantity = ref(1)
const currentImage = ref('')
const activeTab = ref('description')
const selectedSpecs = ref<Record<string, string>>({})
const isWishlisted = ref(false)
const attributeModalVisible = ref(false)
const isBuyNowMode = ref(false)

// 计算属性
const productId = computed(() => Number(route.params.id))

// 方法
const loadProductDetail = async () => {
  if (!isComponentMounted.value) return
  
  loading.value = true
  try {
    const response = await productService.getProductDetail(productId.value)
    
    if (!isComponentMounted.value) {
      loading.value = false
      return
    }
    
    // 后端返回 ProductVO，映射为 ProductDetail
    const vo = response.data.data
    if (vo) {
      // 使用 productImages 数组而不是单个 productImageUrl
      const images = vo.productImages && vo.productImages.length > 0 
        ? vo.productImages.map((img: any) => `http://localhost:8083${img.imageUrl}`)
        : []

      product.value = {
        id: vo.shoeId,
        productId: vo.shoeId,
        name: vo.name,
        description: '',
        price: Number(vo.price),
        originalPrice: Number(vo.discountPrice || vo.price),
        brandId: vo.brand?.brand_id || 0,
        brandName: vo.brand?.brand_name || '无品牌',
        categoryId: vo.type?.typeId || 0,
        categoryName: vo.type?.typeName || '无分类',
        typeId: vo.type?.typeId || 0,
        typeName: vo.type?.typeName || '无类型',
        status: 'active', // 使用固定的状态值
        mainImage: images[0] || '',
        images: images,
        colors:
          vo.availableColors?.map((c) => ({
            colorId: c.colorId,
            colorName: c.colorName,
            status: 'active',
          })) || [],
        sizes:
          vo.availableSizes?.map((s) => ({ sizeId: s.sizeId, shoeSize: s.sizeName, status: 1 })) ||
          [],
        stock: vo.stockInfo ? vo.stockInfo.reduce((total: number, item: any) => total + (item.stockQuantity || 0), 0) : 0,
        sales: vo.salesVolume || 0,
        rating: 5.0, // 默认评分，实际应该从评价表获取
        reviewCount: 0, // 默认评价数，实际应该从评价表获取
        createTime: '',
        updateTime: '',
        specifications: {},
        tags: [],
        isHot: false,
        isNew: false,
        isRecommended: false,
      }
      // 安全地设置当前图片
      currentImage.value = images[0] || ''
      
      // 加载商品详情后，检查收藏状态
      await checkWishlistStatusForProduct()
    }
  } catch (error) {
    productLogger.error('加载商品详情失败:', error)
    ElMessage.error('加载商品详情失败')
  } finally {
    loading.value = false
  }
}

const loadRelatedProducts = async () => {
  if (!isComponentMounted.value || !product.value) return
  
  try {
    const response = await productService.getRelatedProducts(product.value.productId, 4)
    
    if (!isComponentMounted.value) return
    
    // 将 ProductVO 类型转换为 Product 类型
    relatedProducts.value = response.data.data.map((vo: import('@/types').ProductVO) => ({
      id: vo.shoeId,
      productId: vo.shoeId,
      name: vo.name,
      description: '',
      price: Number(vo.price),
      originalPrice: Number(vo.discountPrice || vo.price),
      brandId: vo.brand?.brand_id || 0,
      brandName: vo.brand?.brand_name || '无品牌',
      categoryId: vo.type?.typeId || 0,
      categoryName: vo.type?.typeName || '无分类',
      typeId: vo.type?.typeId || 0,
      typeName: vo.type?.typeName || '无类型',
      status: 'active',
      mainImage: vo.productImageUrl ? `http://localhost:8083${vo.productImageUrl}` : '',
      images: vo.productImageUrl ? [`http://localhost:8083${vo.productImageUrl}`] : [],
      colors: [],
      sizes: [],
      stock: 0, // 暂时设为0，实际应该从库存API获取
      sales: vo.salesVolume || 0,
      rating: 5.0,
      reviewCount: 0,
      createTime: '',
      updateTime: '',
    }))
  } catch (error) {
    productLogger.error('加载相关商品失败:', error)
    // 如果相关推荐失败，使用原来的逻辑作为备选
    try {
      const fallbackResponse = await productService.getProductList({
        categoryId: product.value?.categoryId,
        page: 1,
        size: 4,
      } as any)
      
      if (!isComponentMounted.value) return
      
      relatedProducts.value = fallbackResponse.data.data.list.map((vo: import('@/types').ProductVO) => ({
        id: vo.shoeId,
        productId: vo.shoeId,
        name: vo.name,
        description: '',
        price: Number(vo.price),
        originalPrice: Number(vo.discountPrice || vo.price),
        brandId: vo.brand?.brand_id || 0,
        brandName: vo.brand?.brand_name || '无品牌',
        categoryId: vo.type?.typeId || 0,
        categoryName: vo.type?.typeName || '无分类',
        typeId: vo.type?.typeId || 0,
        typeName: vo.type?.typeName || '无类型',
        status: 'active',
        mainImage: vo.productImages && vo.productImages.length > 0 ? `http://localhost:8083${vo.productImages[0].imageUrl}` : '',
        images: vo.productImages && vo.productImages.length > 0 
          ? vo.productImages.map((img: any) => `http://localhost:8083${img.imageUrl}`)
          : [],
        colors: [],
        sizes: [],
        stock: 0,
        sales: vo.salesVolume || 0,
        rating: 5.0,
        reviewCount: 0,
        createTime: '',
        updateTime: '',
      }))
    } catch (fallbackError) {
      productLogger.error('备选相关商品加载也失败:', fallbackError)
    }
  }
}

const selectSpec = (specName: string, value: string) => {
  selectedSpecs.value[specName] = value
}

const showAttributeModal = () => {
  isBuyNowMode.value = false
  attributeModalVisible.value = true
}

const showBuyNowModal = () => {
  if (!authStore.isLoggedIn) {
    authModal.openLogin('/checkout', '登录后可下单购买')
    return
  }
  isBuyNowMode.value = true
  attributeModalVisible.value = true
}

const handleAddToCartSuccess = (skuId?: number) => {
  // 弹窗组件会处理成功消息，这里可以做其他处理
  if (isBuyNowMode.value) {
    // 【重要】立即购买模式，跳转到购物车页面并传递SKU ID用于默认选中
    // 此功能确保用户立刻购买后，购物车中该商品被自动选中，提升用户体验
    // ⚠️ 请勿删除此逻辑，否则会影响立刻购买功能的完整性
    router.push({
      path: '/cart',
      query: skuId ? { selectSku: skuId.toString() } : {}
    })
  }
}

const handleAddToCart = async () => {
  if (!product.value || !isComponentMounted.value) return

  const result = await cartStore.addToCart(product.value.productId, quantity.value)
  
  if (!isComponentMounted.value) return
  
  if (result.success) {
    ElMessage.success('已添加到购物车')
  } else {
    if ((result as any).needLogin) {
      authModal.openLogin('/cart', '登录后即可将商品加入购物车')
    } else {
      ElMessage.error(result.error || '添加失败')
    }
  }
}

const handleBuyNow = async () => {
  if (!product.value || !isComponentMounted.value) return

  const result = await cartStore.addToCart(product.value.productId, quantity.value)
  
  if (!isComponentMounted.value) return
  
  if (result.success) {
    router.push('/cart')
  } else {
    if ((result as any).needLogin) {
      authModal.openLogin('/cart', '登录后可立即购买')
    } else {
      ElMessage.error(result.error || '添加失败')
    }
  }
}

// 检查商品收藏状态
const checkWishlistStatusForProduct = async () => {
  if (!authStore.user?.id || !product.value) {
    isWishlisted.value = false
    return
  }

  try {
    const response = await checkWishlistStatus(authStore.user.id, product.value.productId)
    if (response.data.code === 200) {
      isWishlisted.value = Boolean(response.data.data)
    } else {
      isWishlisted.value = false
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    isWishlisted.value = false
  }
}

// 切换收藏状态
const toggleWishlist = async () => {
  // 检查用户是否登录
  if (!authStore.user?.id) {
    authModal.openLogin(route.fullPath, '登录后可收藏商品')
    return
  }

  if (!product.value) {
    ElMessage.error('商品信息不存在')
    return
  }

  try {
    if (isWishlisted.value) {
      // 取消收藏
      const response = await removeFromWishlist(product.value.productId, authStore.user.id)
      
      if (response.data.code === 200) {
        isWishlisted.value = false
        ElMessage.success('已取消收藏')
      } else {
        ElMessage.error(response.data.msg || '取消收藏失败')
      }
                    } else {
                  // 添加收藏
                  console.log('添加收藏参数:', {
                    shoeId: product.value.productId,
                    userId: authStore.user.id
                  })
                  
                  const response = await addToWishlist(product.value.productId, authStore.user.id)
                  
                  if (response.data.code === 200) {
                    isWishlisted.value = true
                    ElMessage.success('已加入收藏')
                  } else {
                    console.error('添加收藏失败:', response.data)
                    ElMessage.error(response.data.msg || '添加收藏失败')
                  }
                }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('收藏操作失败')
  }
}

// 页面加载
onMounted(() => {
  loadProductDetail()
})

// 监听商品变化，加载相关商品
// 监听产品变化
watchEffect(() => {
  if (product.value && isComponentMounted.value) {
    loadRelatedProducts()
  }
})

// 组件卸载前清理
onBeforeUnmount(() => {
  isComponentMounted.value = false
})
</script>

<style scoped lang="scss">
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;

  .breadcrumb-section {
    margin-bottom: 20px;
  }

  .product-content {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;

    .product-info {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 40px;

      .product-images {
        width: 100%;
        max-width: 100%;
        overflow: hidden;
        
        .main-image-container {
          width: 100%;
          height: 400px;
          border: 1px solid #eee;
          border-radius: 8px;
          margin-bottom: 20px;
          overflow: hidden;

          .main-image {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }

        .thumbnail-container {
          display: flex;
          gap: 10px;
          overflow-x: auto;
          max-width: 100%;
          padding-bottom: 10px;

          /* 自定义滚动条 */
          &::-webkit-scrollbar {
            height: 6px;
          }
          
          &::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
          }
          
          &::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
            
            &:hover {
              background: #a8a8a8;
            }
          }

          .thumbnail {
            width: 80px;
            height: 80px;
            border: 1px solid #eee;
            border-radius: 4px;
            cursor: pointer;
            object-fit: cover;
            flex-shrink: 0;
            transition: all 0.2s ease;

            &.active {
              border-color: #409eff;
              transform: scale(1.05);
            }

            &:hover {
              border-color: #409eff;
              transform: scale(1.05);
            }
          }
        }
      }

      .product-details {
        .product-title {
          font-size: 24px;
          font-weight: bold;
          color: #333;
          margin: 0 0 10px 0;
        }

        .product-subtitle {
          font-size: 16px;
          color: #666;
          margin: 0 0 20px 0;
        }

        .price-section {
          display: flex;
          align-items: center;
          gap: 15px;
          margin-bottom: 20px;

          .current-price {
            font-size: 32px;
            font-weight: bold;
            color: #ff4d4f;
          }

          .original-price {
            font-size: 20px;
            color: #999;
            text-decoration: line-through;
          }

          .discount-tag {
            background: #ff4d4f;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 14px;
          }
        }

        .rating-section {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 20px;

          .review-count {
            color: #666;
            font-size: 14px;
          }
        }

        .product-attributes {
          margin-bottom: 20px;

          .attribute-row {
            display: flex;
            margin-bottom: 10px;

            .label {
              width: 80px;
              color: #666;
              font-weight: 500;
            }

            .value {
              color: #333;

              &.low-stock {
                color: #ff4d4f;
                font-weight: bold;
              }
            }
          }
        }

        .spec-section {
          margin-bottom: 20px;

          h3 {
            margin: 0 0 15px 0;
            font-size: 16px;
            color: #333;
          }

          .spec-group {
            display: flex;
            align-items: center;
            margin-bottom: 15px;

            .spec-label {
              width: 80px;
              color: #666;
              font-weight: 500;
            }

            .spec-options {
              display: flex;
              gap: 10px;
              flex-wrap: wrap;
            }
          }
        }

        .quantity-section {
          display: flex;
          align-items: center;
          gap: 15px;
          margin-bottom: 30px;

          .label {
            width: 80px;
            color: #666;
            font-weight: 500;
          }

          .stock-info {
            color: #666;
            font-size: 14px;
          }
        }

        .action-buttons {
          display: flex;
          gap: 15px;
          flex-wrap: wrap;

          .el-button {
            height: 44px;
            font-size: 16px;
            min-width: 120px;
            flex: 1;
            transition: all 0.3s ease;
            border-radius: 8px;
            font-weight: 500;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            }

            &:active {
              transform: translateY(0);
            }

            // 触摸设备优化
            @media (hover: none) and (pointer: coarse) {
              min-height: 48px;
              min-width: 140px;
            }

            // 平板设备优化
            @media (min-width: 768px) and (max-width: 1024px) {
              min-width: 130px;
              height: 46px;
              font-size: 15px;
            }

            // 高分辨率屏幕优化
            @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
              border-width: 1px;
              font-weight: 600;
            }
          }

          // 响应式按钮布局
          @media (max-width: 1200px) {
            gap: 12px;
            
            .el-button {
              min-width: 110px;
              font-size: 15px;
            }
          }

          // 超宽屏幕优化
          @media (min-width: 1400px) {
            gap: 20px;
            
            .el-button {
              min-width: 140px;
              height: 48px;
              font-size: 17px;
            }
          }

          @media (max-width: 992px) {
            gap: 10px;
            
            .el-button {
              min-width: 100px;
              font-size: 14px;
              height: 40px;
            }
          }

          // 移动端隐藏桌面按钮
          @media (max-width: 768px) {
            display: none;
          }
        }

        .mobile-action-buttons {
          display: none; /* 默认隐藏 */
          
          // 移动端显示移动端按钮
          @media (max-width: 768px) {
            display: block;
            width: 100%;
            
            .mobile-btn {
              display: block;
              width: 100%;
              height: 56px;
              margin-bottom: 12px;
              border: none;
              border-radius: 12px;
              font-size: 18px;
              font-weight: 600;
              cursor: pointer;
              transition: all 0.2s ease;
              
              &:last-child {
                margin-bottom: 0;
              }
              
              &:hover {
                transform: translateY(-2px);
              }
              
              &:active {
                transform: translateY(0);
              }
            }
          }

          // 小屏幕手机优化
          @media (max-width: 480px) {
            .mobile-btn {
              height: 52px;
              margin-bottom: 10px;
              font-size: 16px;
              border-radius: 10px;
            }
          }
        }
      }
    }
  }

  .product-description {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;

    .description-content {
      padding: 20px 0;
      line-height: 1.8;
    }

    .specs-content {
      padding: 20px 0;
    }

    .reviews-content {
      padding: 20px 0;
    }
  }

  .related-products {
    background: white;
    border-radius: 8px;
    padding: 20px;

    .section-title {
      margin: 0 0 20px 0;
      font-size: 20px;
      font-weight: bold;
      color: #333;
    }

    .products-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 20px;
    }
  }
}

@media (max-width: 768px) {
  .product-detail-container {
    padding: 10px;

    .product-content {
      padding: 15px;

      .product-info {
        grid-template-columns: 1fr;
        gap: 20px;

        .product-images {
          .main-image-container {
            height: 300px;
          }
          
          .thumbnail-container {
            gap: 8px;
            
            .thumbnail {
              width: 70px;
              height: 70px;
            }
          }
        }

        .product-details {
          .product-title {
            font-size: 18px;
          }

          .current-price {
            font-size: 22px;
          }
          
          .action-buttons {
            display: none; /* 小屏幕隐藏桌面按钮 */
          }

          .mobile-action-buttons {
            display: flex; /* 小屏幕显示移动端按钮 */
          }
        }
      }
    }

    .products-grid {
      grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
      gap: 15px;
    }
  }
}

/* 小屏幕手机优化 */
@media (max-width: 480px) {
  .product-detail-container {
    padding: 8px;

    .product-content {
      padding: 10px;

      .product-info {
        gap: 15px;

        .product-images {
          .main-image-container {
            height: 250px;
            margin-bottom: 15px;
          }
          
          .thumbnail-container {
            gap: 6px;
            
            .thumbnail {
              width: 60px;
              height: 60px;
            }
          }
        }

        .product-details {
          .product-title {
            font-size: 18px;
          }

          .current-price {
            font-size: 22px;
          }
        }
      }
    }
  }
}

/* 中等屏幕优化 */
@media (min-width: 769px) and (max-width: 1024px) {
  .product-detail-container {
    padding: 15px;

    .product-content {
      padding: 20px;

      .product-info {
        gap: 30px;

        .product-images {
          .main-image-container {
            height: 350px;
          }
          
          .thumbnail-container {
            gap: 12px;
            
            .thumbnail {
              width: 75px;
              height: 75px;
            }
          }
        }
      }
    }
  }
}

/* 大屏幕优化 */
@media (min-width: 1025px) {
  .product-detail-container {
    padding: 20px;

    .product-content {
      padding: 25px;

      .product-info {
        gap: 40px;

        .product-images {
          .main-image-container {
            height: 400px;
          }
          
          .thumbnail-container {
            gap: 15px;
            
            .thumbnail {
              width: 80px;
              height: 80px;
            }
          }
        }
      }
    }
  }
}
</style>
